package com.hsy.crm.web.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hsy.crm.web.domain.cm.App;
import com.hsy.crm.web.domain.cm.PageResult;
import com.hsy.crm.web.domain.cm.Unified;
import com.hsy.crm.web.domain.entity.Account;
import com.hsy.crm.web.domain.entity.OrderAccount;
import com.hsy.crm.web.domain.po.account.AccountPagePo;
import com.hsy.crm.web.domain.vo.account.AccountPageVo;
import com.hsy.crm.web.mapper.AccountMapper;
import com.hsy.crm.web.mapper.OrderAccountMapper;
import com.hsy.crm.web.service.base.BaseService;
import com.hsy.crm.web.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountService extends BaseService<Account> {

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    OrderAccountMapper orderAccountMapper;

    public Unified<Integer> deleteAccount(Account account) {
        Unified<Integer> unified = new Unified<>();

        OrderAccount orderAccount = new OrderAccount();
        orderAccount.setAccountId(account.getId());
        orderAccount.setCustomerId(account.getCustomerId());
        List<OrderAccount> orderAccounts = orderAccountMapper.select(orderAccount);
        if(ListUtils.isEmpty(orderAccounts)){
            this.delete(account);
        }else{
            unified.setResult(App.BussError.ACCOUNT_DELETE_ORDER.getCode());
        }
        return unified;
    }

    public PageResult<AccountPagePo> page(AccountPageVo accountPageVo) {
        Page page = PageHelper.startPage(accountPageVo.getPage(),accountPageVo.getLimit());
        PageResult<AccountPagePo> pageResult = new PageResult<>();
        pageResult.setRows(accountMapper.page(accountPageVo));
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    public void updateBalance(String customerId, Long accountId,Long price,int direction){
        Account account = new Account();
        account.setId(accountId);
        account.setCustomerId(customerId);
        account.setBalance(price);
        if( direction == App.Direction.ADD ){
            accountMapper.addBalance(account);
        }else if( direction == App.Direction.SUB ){
            accountMapper.subBalance(account);
        }
    }

}
